# coding: utf-8
from sqlalchemy import BigInteger, Column, String, text, exists
import goodDesignImage2018Spider.dao.dbConfig as mysqlConfig

# 对象的基类
Base = mysqlConfig.get_base()
# 初始化数据库连接
engine = mysqlConfig.get_eng()
# 创建DBSession类型
DBSession = mysqlConfig.get_db_session()
metadata = Base.metadata


class CaipuInfo(Base):
    __tablename__ = 'caipu_info'
    __table_args__ = {'comment': '菜谱表'}

    caipu_info_id = Column(BigInteger, primary_key=True, unique=True)
    caipu_title = Column(String(200, 'utf8mb4_general_ci'), nullable=False, server_default=text("''"), comment='菜谱标题')
    caipu_third_source_id = Column(BigInteger, server_default=text("'0'"), comment='第三方系统资源id')
    caipu_main_ingredients_json = Column(String(2000, 'utf8mb4_general_ci'), server_default=text("''"), comment='主料')
    caipu_others_ingredients_json = Column(String(2000, 'utf8mb4_general_ci'), server_default=text("''"), comment='辅料')
    caipu_intro = Column(String(2000, 'utf8mb4_general_ci'), server_default=text("''"), comment='菜谱简介')
    caipu_tips = Column(String(2000, 'utf8mb4_general_ci'), server_default=text("''"), comment='菜谱技巧')
    caipu_tech = Column(String(200, 'utf8mb4_general_ci'), comment='菜谱工艺信息')
    caipu_category_id_1 = Column(BigInteger, comment='菜谱分类id1')
    caipu_category_id_2 = Column(BigInteger, comment='菜谱分类id2')

    #  插入菜谱
    @staticmethod
    def add_cp_info(cp):
        session = DBSession()
        session.add(cp)
        session.flush()
        session.commit()
        id = cp.caipu_info_id
        session.close()
        return id

    #  根据第三方id查询菜谱是否存在
    @staticmethod
    def check_cp_info_by_third_id(third_id):
        session = DBSession()
        cp_exists = session.query(
            exists().where(CaipuInfo.caipu_third_source_id == third_id)
        ).scalar()
        session.close()
        return cp_exists
